<?php

namespace app\common\service;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\order\logic\OrderShipLogic;
use app\order\logic\OrderWhLogic;
use app\order\model\SkuWeightSize;
use app\common\service\ConstantOrderService;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;

/*
 *  金蚁api:http://qqwy.3wms.com/Pages/DocApi/HomePage.html
 */

class JinyiApiService
{
    protected $url = null;

    public function __construct()
    {
        $this->url = Config('Logisticskey.JY.url');
    }



    /**
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @desc  生成订单
     */
    public function createOrder($order)
    {
        htmlLog(['order'=>$order],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        $return = [
            'order_id'     => $order['order_id'],
            'shop_id'      => $order['shop_id'],
            'warehouse_id' => $order['warehouse_id'],
            'data'         => '',
            'return0'      => '',
            'return1'      => '',
        ];
        //获取组装数据
        $JsonData = self::buildJsonData($order);

        //sku信息组装  2024-05-10 查看是否拆分sku
        $exist_split_sku = Db::name('order_split_ship')->where(['order_id'=>$order['order_id']])->find();
        if($exist_split_sku){
            $skuInfos   = $order['skuinfo'];
            $skuInfos   = explode(',',$skuInfos);
        }else{
            $skuInfos   = Db::name('order_info')->where('order_id', $order['order_id'])->column('seller_sku');
        }
        $orderDetail_arr = $arr = $OrderDetail = [];

        foreach($skuInfos as $v){
            if($exist_split_sku){
                $orderDetail_arr[] = get_seller_sku_change($v);
            }else{
                $orderDetail_arr[] = get_seller_sku($v);
            }
        }

        if(!$orderDetail_arr)  return true;

        //数组整合
        foreach($orderDetail_arr as $v){
            if(isset($v[0]) && is_array($v[0])){
                foreach($v as $value){
                    $arr[] = $value;
                }
            }else{
                    $arr[] = $v;
            }
        }

        foreach($arr as $v){
            $OrderDetail[] = [
                   'Wt_SKU'   => $v['sku'],
                   'Wt_Number'=> $v['qtyOrdered'],
            ];
        }


        $OrderDetail                 = self::getQtyOrdered($OrderDetail);
        $JsonData["ItemDetailsList"] = $OrderDetail;
        //手动选择金蚁渠道
        $resDeliveryTxt  = self::getDeliveryTxt($order['golden_ant']);
        $JsonData["Wt_DeliveryTxt"]  = $resDeliveryTxt;

        //刷单
        if ($order['brush_status'] == "brush") {
                $brushData["Wt_SKU"]        = "SKU000135";
                $brushData["Wt_Number"]     = 1;
                $JsonData["ItemDetailsList"]= [$brushData];
                $JsonData["Wt_DeliveryID"]  = 2011;
                $JsonData["Wt_DeliveryTxt"] = "HWC-SD";
                $JsonData["AddressReceived"]['Wt_Adress']      = "15780 El Prado Rd，Chino, CA  91708";
                $JsonData["AddressReceived"]['Wt_Phone']       = "7143638860";
                $JsonData["AddressReceived"]['Wt_Email']       = "Ahead four+HTF";
                $JsonData["AddressReceived"]['Wt_CompanyName'] = "Ahead four+HTF";
            }

        if ($order['shipping_type'] == "TIKTOK") {
            $JsonData["AddressReceived"]['Wt_ZipCode'] = "28205";
            $JsonData["AddressReceived"]['Wt_Adress']  = "North Carolina Charlotte Mecklenburg 1419 Elkin Lane Apt 3";
            $JsonData["Wt_DeliveryTxt"]                = "TiK-shop";
            $JsonData["Wt_DeliveryID"]                 = "2015";
            $JsonData["Wt_LabelPathAPI"]               = $order['shipping_documents'];
        }


        if ($order['type'] == 2){ // $specialspecial_state = 1; TIK面单发货,强制发货
                $JsonData["AddressReceived"]['Wt_ZipCode'] = "28205";
                $JsonData["AddressReceived"]['Wt_Adress']  = "15780 El Prado Rd，Chino, CA  91708";
                $JsonData["Wt_DeliveryTxt"]                = "TiK-shop";

                $JsonData["AddressReceived"]['Wt_Email']   = "Ahead four+HTF";
                $JsonData["AddressReceived"]['Wt_Phone']   = "7143638860";

                //新增 跟踪号跟面单不能为空
                if (empty($order['tracking_number']) || empty($order['shipping_documents'])) {
                    $return['code'] = 2; //面单跟踪号问题
                    $return['msg'] = "发货失败！面单跟踪号等数据未同步，请等待五分钟";
                    self::doInsertOrderShipLog($return,$order);
                    return true;
                }
                $JsonData["Wt_LogisticsOrderNo"] = $order['tracking_number'];
                $JsonData["Wt_LabelPathAPI"]     = $order['shipping_documents'];
            }

           // if ($order['modifystatus'] == "hidden")  self::handleUpdateOrder($order=[]);  //手动修改订单信息后发货  //后续加功能  2024-03-29
            //订单数据推送到金蚁 2024-03-30
            $url = $this->url . Config('Logisticskey.JY.create_order_path');
            $JsonData = (is_array($JsonData)) ? json_encode($JsonData, JSON_UNESCAPED_UNICODE) : $JsonData;
            $JsonDatas['JsonData'] = $JsonData;

            htmlLog(['url'=>$url,'params'=>$JsonDatas,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
            $response = HttpUtil::postUrlJY($url, $JsonDatas);
            $result   = json_decode($response, true);
            htmlLog(['response'=>$result,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
            //返回结果处理;
            if ($result && $result['Message'] == "操作成功") {
                 self::handleSuccessShipping($response,$order,$JsonDatas);
            } else {
                 self::handleFailedShipping($response,$order,$return);
            }
            return true;
    }


    /**
     * @desc  构建 JsonData返货参数处理
     * @date  2024-03-30
     * @author luckyXiong
     */
    public function buildJsonData($order=[]){

        $JsonData                             = [];

        $JsonData["Wt_WarehouseTxt"]            = Config('Logisticskey.JY.Wt_WarehouseTxt');
        $JsonData["Wt_IsCOD"]                   = Config('Logisticskey.JY.Wt_IsCOD');
        $JsonData["Wt_PlatformReferenceNumber"] = $order['order_id'];
        //1 存草稿箱  2 待分拣
        $JsonData["Wt_StatusID"]                = Config('Logisticskey.JY.Wt_StatusID');
        //正常情况
        $JsonData["Wt_DeliveryID"]              = Config('Logisticskey.JY.Wt_DeliveryID');
        $JsonData["Wt_DeliveryTxt"]             = Config('Logisticskey.JY.Wt_DeliveryTxt');


        $JsonData["Wt_DeclaredValue"]           = Config('Logisticskey.JY.Wt_DeclaredValue');
        $JsonData["Wt_InsuranceTrue"]           = Config('Logisticskey.JY.Wt_InsuranceTrue');
        $JsonData["ItemDetailsList"]            = [];
        //收货人及公司处理
        $user_name = $this->name_deal($order['name']) ?? $order['name'];
        $JsonData["AddressReceived"]['Wt_Addressee']   = $user_name;
        $JsonData["AddressReceived"]['Wt_CompanyName'] = $user_name;
        //收货人手机号处理(确认去掉(+1)后打开)
        $phone_1 = '';
        if (!empty($order['phone_number'])) {
            $phone_1 = explode('(+1)', $order['phone_number']);
            $phone_1 = $phone_1[1] ?? $phone_1[0];
        }

        $JsonData["AddressReceived"]['Wt_Phone']   = $phone_1;
        $JsonData["AddressReceived"]['Wt_Email']   = $order['buyer_email'];
        $JsonData["AddressReceived"]['Wt_ZipCode'] = $order['postal_code'];
        $JsonData["AddressReceived"]['Wt_Adress']  = $order['address_detail'];

        $JsonData["AddressReceived"]['Wt_CountryTxt']   = '美国';
        //美国州处理
        $state = Db::name('usstate')->where('name_key', $order['state'])->find();
        $state = $state['name_value'] ?? $order['state'];
        $JsonData["AddressReceived"]['Wt_ProvinceTxt'] = $state;
        $JsonData["AddressReceived"]['Wt_CityTxt']     = $order['city'];
        $JsonData["AddressReceived"]['Wt_AreaTxt']     = $order['county'];
        // 其他逻辑处理...
        return $JsonData;
    }






    /**
     * @desc 获取金蚁渠道
     * @date  2024-03-30
     * @author luckyXiong
     */
    public function getDeliveryTxt($golden_ant=''){
        $arr = [
            '1003' => "HWC-TK",
            '2015' => "TiK-shop",
            '2011' => "HWC-SD",
            '1010' => "HWC-artificial",
            '1009' => "海外仓一6日签",
        ];
        return $arr[$golden_ant]??'';
   }


    public function doInsertOrderShipLog($return=[],$order=[]){
       $updateShip['status'] = 2;
       $updateShip['time']   = time();
       $updateShip['msg']    = $return['msg'];
       $exist_ship =  Db::name('order_ship')->where('order_id', $order['order_id'])->find();
       if($exist_ship){
           Db::name('order_ship')->where('order_id', $order['order_id'])->update($updateShip);
       }else{
            Db::name('order_ship')->insert([
                    'order_id'    =>$order['order_id'],
                    'shop_id'     =>$order['shop_id'],
                    'warehouse_id'=>$order['warehouse_id'],
                    'status'      =>2,
                    'time'        =>time(),
                    'msg'         =>$return['msg'],
                    'type'        =>$order['type'],
            ]);
       }
       OrderShipLogic::insertOrderShipLog($return);
   }

    /**
     * @desc 处理发货成功的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleSuccessShipping($response=[],$order=[],$JsonDatas=[])
    {
        $result   = json_decode($response, true);
        $tracking_number   = $result['Data']['Wt_ID']??'';
        $return['code']    = 3;
        $return['msg']     = "回传物流单号";
        $return['return0'] = $response;
        $return['data']    = $tracking_number;
        //有跟踪号代表发货了
        $msg                            = '金蚁自发货，已发货';
        $status                         = 3;
        if($order['type'] == 2){ //金蚁走官方面单发货，已返回真实运单
            $return['msg']         = "强制金蚁发货成功，已回传面单，不继续进行后续操作";
            $return['return0']     = json_encode($JsonDatas);
            $msg                   = "发货成功，金蚁走官方面单发货,无需后续刷运单号";
            $status                = 5;
            $tracking_number       = Db::name('order')->where('order_id',$order['order_id'])->value('tracking_number');
        }
        $exist_ship = Db::name('order_ship')->where('order_id', $order['order_id'])->find();
        if(!$exist_ship){
            Db::name('order_ship')->where('order_id', $order['order_id'])->insert([
                'order_id'        =>$order['order_id'],
                'shop_id'         =>$order['shop_id'],
                'warehouse_id'    =>$order['warehouse_id'],
                'status'          =>$status,
                'time'            =>time(),
                'tracking_number' =>$tracking_number,
                'msg'             =>$msg,
                'type'            =>$order['type']
                ]
            );
        }else{
            Db::name('order_ship')->where('order_id', $order['order_id'])->update([
                'status'           =>$status,
                'time'             =>time(),
                'warehouse_id'     =>$order['warehouse_id'],
                'tracking_number'  =>$tracking_number,
                'msg'              =>$msg,
            ]
            );
        }
        if($order['type'] == 1){ //金蚁自主发货
            Db::name('order')->where('order_id', $order['order_id'])->update([
                'tracking_number'=>$tracking_number
            ]);
        }

         Db::name('order')->where('order_id', $order['order_id'])->update([
          'send_status'=>1
         ]);

        //更新仓库ID
        Db::name('order_split_ship')
            ->where([
                'order_id'  =>$order['order_id'],
                'seller_sku'=>$order['skuinfo'],

            ])
            ->update(['warehouse_id'=>$order['warehouse_id'],'status'=>1]);


        OrderShipLogic::insertOrderShipLog($return);
    }

    /**
     * @desc 处理发货失败的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleFailedShipping($response='',$order=[], $return=[])
    {
        $result               = json_decode($response, true);
        $return['code']       = 2;
        $return['msg']        = "错误：" . $result['Message'];
        $return['return0']    = $response;
        $updateShip['status'] = 2;
        $updateShip['time']   = time();
        $updateShip['msg']    = $return['msg'];
        $updateShip['warehouse_id'] = $order['warehouse_id'];
        $exist_ship = Db::name('order_ship')->where('order_id',$order['order_id'])->find();
        if(!$exist_ship){
            Db::name('order_ship')->insert([
                'order_id'    =>$order['order_id'],
                'shop_id'     =>$order['shop_id'],
                'warehouse_id'=>$order['warehouse_id'],
                'status'      =>2,
                'time'        =>time(),
                'msg'         =>$response,
                'type'        =>$order['type'],
            ]);
        }else{

            //异常重发页面失败了才改为已处理
            if($order['fail_status']==6){
                $updateShip['status'] = 5; //失败改为已处理
            }
            Db::name('order_ship')->where('order_id', $order['order_id'])->update($updateShip);
        }

        Db::name('order')->where('order_id', $order['order_id'])->update([
            'send_status'=>2
        ]);

        //更新仓库ID
        Db::name('order_split_ship')
            ->where([
                'order_id'  =>$order['order_id'],
                'seller_sku'=>$order['skuinfo'],

            ])
            ->update(
                [
                    'warehouse_id'   =>$order['warehouse_id'],
                    'msg'            =>$result['Message'],
                    'update_time'    =>date("Y-m-d H:i:s", time()),
                ]);

        OrderShipLogic::insertOrderShipLog($return);
    }



    /**
     * @desc 处理发货成功的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleSuccessWhShipping($response=[],$order=[],$JsonDatas=[])
    {
        $result            = json_decode($response, true);
        $tracking_number   = $result['Data']['Wt_ID'];
        $return['code']    = 3;
        $return['msg']     = "回传物流单号";
        $return['return0'] = $response;
        $return['data']    = $tracking_number;
        //有跟踪号代表发货了
        $update['tracking_beforehand'] = 3;
        $update['updatetime'] = time();
        $update['tracking_number'] = $tracking_number;
        $update['warehouse_id']    = $order['warehouse_id'];
        $update['msg'] = "回传物流单号";
        Db::name('orderwh')->where('order_id', $order['order_id'])->update($update);
        OrderWhLogic::insertOrderWhLog($return);
    }

    /**
     * @desc 处理发货失败的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleFailedWhShipping($order=[], $response=[],$return=[])
    {

        $result            = json_decode($response, true);
        $return['code']    = 2;
        $return['msg']     = "错误：" . $result['Message'];
        $return['warehouse_id']  = $order['warehouse_id'];
        $return['return0'] = $response;
        $update['tracking_beforehand'] = 2;
        $update['updatetime'] = time();
        $update['warehouse_id']    = $order['warehouse_id'];
        $update['msg'] = "错误：" . $result['Message'];
        Db::name('orderwh')->where('order_id', $order['order_id'])->update($update);
        OrderWhLogic::insertOrderWhLog($return);
    }








    /**
     * @desc 手动修改订单发货处理
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleUpdateOrder($order=[]){
        $OrderDetail2 = [];
        if (!empty($order['skuinfo'])) {
            $skuinfos = explode(',', $order['skuinfo']);
            foreach ($skuinfos as $ksku => $vsku) {
                $test = [];
                $test["Wt_SKU"] = $vsku;
                $test["Wt_Number"] = 1;
                $OrderDetail2[] = $test;
            }
        }
       return $OrderDetail2;
    }



    /**
     * @param $order
     * @desc 订单回传
     * @date 2024-05-23
     */
    public function update_tracking_number($order=[])
    {

        $order_id          = $order['order_id']??'';
        if (!empty($order_id)) {
            $where[] = ['order_ship.order_id', '=', $order_id];
        }
        //查询需要回传物流单号的订单  通过仓库编码更新
        $where[]  = ['status', '=', 3];
        $where[]  = ['warehouse_id', '=', 3];
        $where[]  = ['tracking_number', '>', 0];
        $where[]  = ['type', '=', 1]; //自发货的订单
        $orders   = Db::name('order_ship')->where($where)->order('time asc')->limit(50)->select()->toarray();
        if(!$orders)    return json(DefaultResponse(201, false, '暂无数据!'));
        //通过查询的单号取接口数据循环更新
        foreach ($orders as $order) {
            $order['type']  = 1;
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_JINYI_TRACKING_NUMBER_UPDATE_QUEUE,
                $order,
                false
            );
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
     * @param $order
     * @desc 网红订单回传
     * @date 2024-05-23
     */
    public function update_tracking_number_wh($order=[])
    {
        $order_id          = $order['order_id']??'';
        if (!empty($order_id)) {
            $where[] = ['order_id', '=', $order_id];
        }
        //查询需要回传物流单号的订单  通过仓库编码更新
        $where[] = ['tracking_beforehand', '=', 3];
        $where[] = ['warehouse_id', '=', 3];
        $where[] = ['tracking_number', '>', 0];
        $orders  = Db::name('orderwh')->where($where)->field('id,order_id,warehouse_id,tracking_number')->order('createtime asc')->select();
        $orders  = objectToArray($orders);
        if(!$orders)    return json(DefaultResponse(201, false, '暂无数据!'));
        //通过查询的单号取接口数据循环更新
        foreach ($orders as $order) {
            $order['type']  = 2;//网红订单
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_JINYI_TRACKING_NUMBER_UPDATE_QUEUE,
                    $order,
                    false
                );
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }


    /**
     * @desc    金蚁自发货物流单号回传mq消费方法
     * @date    2024-04-13
     * @author  luckyXiong
     */
    public function tracking_number_update_consumer($order=[]){
        $type                   = $order['type']??'';  //  type 1:正常自发货  2:网红自发货
        $shop_id                = $order['shop_id']??'';
        $base_url               = Config('Logisticskey.JY.url');
        $path                   = Config('Logisticskey.JY.get_order_path');
        $url                    = $base_url.$path.'?ID=' . $order['tracking_number'] . '&Prop=TrackList';
        $response               = HttpUtil::postUrlJY($url,['JsonData'=>[]]);
        $result                 = json_decode($response, true);
        htmlLog(['params'=>$order,'response'=>$result],OPERATE_LOG . date('Ym') . '/tracking_number_update_consumer/' . date('Ymd') . '.txt');
        $Wt_LogisticsOrderNo    = $result['Data']['Wt_LogisticsOrderNo']??'';
        if(isset($result['Status']) && $result['Status']=='1000'){
            self::add_jin_yi_success_log($type,$order['order_id'],$Wt_LogisticsOrderNo,$shop_id,$order['warehouse_id']);
        }else{
            self::add_jin_yi_error_log($type,$result['Message'],$order['order_id'],$Wt_LogisticsOrderNo,$shop_id,$order['warehouse_id']);
        }
    }


    /**
     * @desc  记录金蚁回传单号
     * @date  2024-04-13
     * @author  luckyXiong
     */
    public function add_jin_yi_error_log($type='',$Message='',$order_id='',$Wt_LogisticsOrderNo='',$shop_id='',$warehouse_id=''){
        switch($type){
               case 1:
                   Db::name('order_ship')->where('order_id', $order_id)->update([
                       'status'  => 3,
                       'msg'     => $Message,
                       'time'    => time(),
                   ]);
                   $return['code']            = 3;
                   $return['shop_id']         = $shop_id;
                   $return['order_id']        = $order_id;
                   $return['warehouse_id']    = $warehouse_id;
                   $return['msg']             = $Message;
                   $return['data']            = $Wt_LogisticsOrderNo;
                   OrderShipLogic::insertOrderShipLog($return);
                   break;
            case   2:
                Db::name('orderwh')->where(['order_id' => $order_id])->update([
                        'tracking_beforehand'  => 2,
                        'msg'                  => $Message,
                        'updatetime'           => time()
                    ]);
                $return['code']            = 2;
                $return['shop_id']         = $shop_id;
                $return['order_id']        = $order_id;
                $return['warehouse_id']    = $warehouse_id;
                $return['msg']             = $Message;
                $return['data']            = $Wt_LogisticsOrderNo;
                OrderWhLogic::insertOrderWhLog($return);
                break;
        }
    }


    /**
     * @desc  记录金蚁回传单号
     * @date  2024-04-13
     * @author  luckyXiong
     */
    public function add_jin_yi_success_log($type='',$order_id='',$Wt_LogisticsOrderNo='',$shop_id='',$warehouse_id=''){
        $old_tracking    =  Db::name('order_ship')->where('order_id', $order_id)->find();
        $old_tracking_wh =  Db::name('orderwh')->where('order_id', $order_id)->find();
        htmlLog(['type'=>$type,'order_id'=>$order_id,'Wt_LogisticsOrderNo'=>$Wt_LogisticsOrderNo,'shop_id'=>$shop_id,'warehouse_id'=>$warehouse_id],OPERATE_LOG . date('Ym') . '/add_jin_yi_success_log/' . date('Ymd') . '.txt');
        switch($type){
            case 1: //自发货
                if(preg_match("/^9\d{9,}$|^42\d{9,}$/", $Wt_LogisticsOrderNo)){
                    //推送回传单号到tik
                    $info = [
                        'order_id'        =>$order_id,
                        'shop_id'         =>$shop_id,
                        'tracking_number' =>$Wt_LogisticsOrderNo,
                    ];
                    $res  = self::order_tracking_number_tik_back($info);
                    if(isset($res['message'])&& in_array($res['message'],['Success','package already rts','already rts'])){
                        $Message         = '金蚁物流单号回传完成';
                        $status          = 4;
                        $tracking_number = $Wt_LogisticsOrderNo;
                        $code            = 4;
                        //更新订单主表
                        Db::name('order')->where('order_id', $order_id)->update([
                            'status'              => 'AWAITING_COLLECTION',
                            'tracking_number'     =>  $Wt_LogisticsOrderNo,
                        ]);
                    }else{
                        $Message         = '同步发货状态失败';
                        $status          = 2;
                        $tracking_number = $Wt_LogisticsOrderNo;
                        $code            = 2;
                    }
                }else{
                    $Message           = '物流单号生成中';
                    $status            = 3;
                    $tracking_number   = $old_tracking['tracking_number']??'';
                    $code              = 3;
                }

                $exist_ship = Db::name('order_ship')->where('order_id', $order_id)->find();
                if($exist_ship){
                    Db::name('order_ship')->where('order_id', $order_id)->update([
                        'status'              => $status,
                        'tracking_number'     => $tracking_number,
                        'msg'                 => $Message,
                        'time'                => time()
                    ]);
                }

                $return['code']   = $code;
                $return['shop_id']= $shop_id;
                $return['order_id'] = $order_id;
                $return['warehouse_id']= $warehouse_id;
                $return['msg']    = $Message;
                $return['data']   = $Wt_LogisticsOrderNo;
                OrderShipLogic::insertOrderShipLog($return);
                break;
            case 2:   //网红发货
                $old_tracking_wh['tracking_beforehand'] = $old_tracking_wh['tracking_beforehand']??'';
                $old_tracking_wh['tracking_number'] = $old_tracking_wh['tracking_number']??'';
                $Message           =  $Wt_LogisticsOrderNo      ? '物流单号回传完成' : '物流单号生成中';
                $status            =  $Wt_LogisticsOrderNo      ? 4 : $old_tracking_wh['tracking_beforehand'];
                $tracking_number   =  $Wt_LogisticsOrderNo      ? :   $old_tracking_wh['tracking_number'];
                $code              =  $Wt_LogisticsOrderNo      ? 4 : 2;
                Db::name('orderwh')->where('order_id', $order_id)->update([
                    'tracking_beforehand' => $status,
                    'tracking_number'     => $tracking_number,
                    'msg'                 => $Message,
                    'updatetime'          => time()
                ]);
                $return['code']   = $code;
                $return['shop_id']= $shop_id;
                $return['order_id'] = $order_id;
                $return['warehouse_id']= $warehouse_id;
                $return['msg']    = $Message;
                $return['data']   = $Wt_LogisticsOrderNo;
                OrderWhLogic::insertOrderWhLog($return);
                break;
        }
    }


    /**
     * @desc 金蚁物流单号获取后推送到TIK
     * @Date 2024-4-15
     * @Author  luckyXiong
     */
    public function order_tracking_number_tik_back($info=[]){
        if(!$info)   return  true;
        $field       = 'id,app_key,cipher,app_secret,access_token';
        $account     = Db::name('shops')->where('id',$info['shop_id'])->field($field)->find();
        $base_url    = Config('Logisticskey.TIKTOK.basic_url');
        $path        = Config('Logisticskey.TIKTOK.orders_fulfillment_path');
        $delivery_option_id  = Config('Logisticskey.TIKTOK.delivery_option_id');
        $path = $path . $info['order_id'] . '/packages';
        $sign = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '{"shipping_provider_id":"' . $delivery_option_id . '","tracking_number":"' . $info['tracking_number'] . '"}' . $account['app_secret'];
        $sign = hash_hmac('sha256', $sign, $account['app_secret']);
        $url = $base_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        htmlLog(['shipping_provider_id'=>$delivery_option_id,'tracking_number'=>$info['tracking_number']],OPERATE_LOG . date('Ym') . '/order_tracking_number_tik_back/' . date('Ymd') . '.txt');
        return HttpUtil::tikPostUrl($url, ['shipping_provider_id'=>$delivery_option_id,'tracking_number'=>$info['tracking_number']], $account['access_token']);
    }






    //姓名拉丁文处理
    public function name_deal($str = '')
    {
        $rst1 = iconv("utf-8", "ascii//TRANSLIT//IGNORE", $str);
        $result = preg_replace("/[^a-zA-Z0-9\s]/", "", $rst1);
        return $result;
    }

    //生成订单-网红小店
    public function createOrderWh($order)
    {
        $return = [
            'order_id' => $order['order_id'],
            'shop_id'  => $order['shop_id']??'',
            'data'     => '',
            'return0'  => '',
            'return1'  => '',
        ];


        //获取组装数据
        $JsonData  = self::buildJsonData($order);
        if(!$order['skuinfo'])    return true;
        $orderinfo = explode(',', $order['skuinfo']);
        foreach ($orderinfo as  $v) {
            $orderDetail_arr[] = get_seller_sku($v);
        }

        if(!$orderDetail_arr)  return true;

         //数组整合
         foreach($orderDetail_arr as $v){
            if(isset($v[0]) && is_array($v[0])){
                foreach($v as $value){
                    $arr[] = $value;
                }
            }else{
                $arr[] = $v;
            }
        }

         foreach($arr as $v){
            $OrderDetail[] = [
                'Wt_SKU'   => $v['sku'],
                'Wt_Number'=> $v['qtyOrdered'],
            ];
        }

          $JsonData["ItemDetailsList"] = $OrderDetail;


           if (empty($JsonData["ItemDetailsList"])){
            $return['code']     = 2; //SKU问题
            $return['msg']      = "发货失败！SKU未填";
            self::doInsertOrderWhLog($return);
           }

            //先处理重复值
            $OrderDetail2 = $JsonData["ItemDetailsList"];
            $OrderDetail2 =self::getQtyOrdered($OrderDetail2);
            $JsonData["ItemDetailsList"] = $OrderDetail2;
            $JsonData = (is_array($JsonData)) ? json_encode($JsonData, JSON_UNESCAPED_UNICODE) : $JsonData;
            $JsonDatas['JsonData'] = $JsonData;
            $url = $this->url . Config('Logisticskey.JY.create_order_path');
            htmlLog(['url'=>$url,'order_param'=>$order,'params'=>$JsonDatas,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrderWh/' . date('Ymd') . '.txt');
            $response = HttpUtil::postUrlJY($url, $JsonDatas);
            $result   = json_decode($response, true);
            htmlLog(['response'=>$result,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrderWh/' . date('Ymd') . '.txt');
            //记录日志
            if ($result && $result['Message'] == "操作成功") {
                  self::handleSuccessWhShipping($response,$order,$JsonDatas);
            } else {
                  self::handleFailedWhShipping($order, $response,$return);
            }
           return true;
    }



    /**
     * @desc 数据统计
     * @date 2024-02-22
     */
    public function getQtyOrdered($info)
    {
        $outputArray = [];
        foreach ($info as $item) {
            $sku = $item['Wt_SKU'];
            if (isset($outputArray[$sku])) {
                $outputArray[$sku]['Wt_Number'] += $item['Wt_Number'];
            } else {
                $outputArray[$sku] = $item;
            }
        }
        return array_values($outputArray);
    }

    /**
     * @desc 数据统计
     * @date 2024-03-30
     * @author luckyXiong
     */
    public function doInsertOrderWhLog($return=[],$order=[]){
        $update['status'] = ConstantOrderService::$ship_status_waiting;
        $update['time']   = time();
        $update['msg']    = $return['msg'];
        Db::name('orderwh')->where('order_id', $order['order_id'])->update($update);
        OrderWhLogic::insertOrderWhLog($return);
    }


}
